package com.esiran.payadmin.service.impl;

import com.esiran.payadmin.exception.APIRespException;
import com.esiran.payadmin.model.Order;
import com.esiran.payadmin.service.WechatPayService;
import com.esiran.payadmin.wechat.SiteWXPayConfig;
import com.esiran.payadmin.wechat.WXPay;
import com.google.gson.Gson;
import okhttp3.OkHttpClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatPayServiceImpl implements WechatPayService {
    private static final OkHttpClient okHttpClient;
    private static final Gson gson;
    static {
        okHttpClient = new OkHttpClient();
        gson = new Gson();
    }
    @Override
    public Map<String,String> doPayOrder(Order order) throws APIRespException {
        return doPayOrder(order,"http://test.esiran.com/api/callback/wechat");
    }

    @Override
    public Map<String, String> doPayOrder(Order order, String notifyUrl) throws APIRespException {
        if (order == null){
            throw new APIRespException("发起支付失败",-1002);
        }
        if (notifyUrl == null){
            throw new APIRespException("发起支付失败",-1003);
        }
        SiteWXPayConfig config = new SiteWXPayConfig();
        try {
            WXPay wxpay = new WXPay(config);
            Map<String, String> data = new HashMap<>();
            data.put("body", order.getGoodsName());
            data.put("out_trade_no", order.getNum());
            data.put("device_info", "WEB");
            data.put("fee_type", "CNY");
            data.put("total_fee", order.getAmount().toString());
            data.put("spbill_create_ip", "123.12.12.123");
            data.put("notify_url", notifyUrl);
            data.put("trade_type", "NATIVE");
            data.put("product_id", "mer:".concat(order.getNum()));
            return wxpay.unifiedOrder(data);
        }catch (Exception e){
            e.printStackTrace();
            throw new APIRespException("发起支付失败",-1003);
        }
    }
}
